#!/usr/bin/env python

import socket
import os

skybot_server = 'SERVER_IP'
port = 7110
chat_name = "opsview"

# Debugging stuff
# Uncoment the following section
'''import logging
logger = logging.getLogger('SkyBot')
hdlr = logging.FileHandler('/var/tmp/SkyBot.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
for name, value in os.environ.items():
    d = name+":\t"+value
    logger.debug(d)'''

# Gather information from our surroundings:
notification_type = os.getenv('NAGIOS_NOTIFICATIONTYPE')
service_description = os.getenv('NAGIOS_SERVICEDESC')
hostname = os.getenv('NAGIOS_HOSTNAME')
service_state = os.getenv('NAGIOS_SERVICESTATE')
service_info = os.getenv('NAGIOS_SERVICEOUTPUT')
host_state = os.getenv('NAGIOS_HOSTSTATE')
host_acknowledged_by = os.getenv('NAGIOS_NOTIFICATIONAUTHORALIAS')
service_acknowledged_by = os.getenv('NAGIOS_SERVICEACKAUTHORALIAS')
service_ack_comment = os.getenv('NAGIOS_SERVICEACKCOMMENT')
host_ack_comment = os.getenv('NAGIOS_HOSTACKCOMMENT')


# Decisions. Decisions. Decisions.
# Check to see if it aproblem or acknowledgment,
# if it concerns a host (ServiceDescription will be empty) or a sevice
# and then craft the appropriate notification message.
if notification_type == 'PROBLEM':
    if service_description == '' or service_description is None:
        notification = "ALERT: Host " + hostname + " is " + host_state
    else:
        notification = ("ALERT: " + service_description + " on " + hostname + " is " + service_state +
                        "\nInformation: " + service_info)
elif notification_type == 'ACKNOWLEDGEMENT':
    if service_description == '' or service_description is None:
        notification = ("ACK: Host " + hostname + " has been acknowledged by " + host_acknowledged_by +
                        "\nComment: " + host_ack_comment)
    else:
        notification = ("ACK: " + service_description + " on " + hostname + " has been acknowledged by " +
                        service_acknowledged_by + "\nComment: " + service_ack_comment)
elif notification_type == 'RECOVERY':
    if service_description == '' or service_description is None:
        notification = "RECOVERY: Host " + hostname + " is " + host_state
    else:
        notification = ("RECOVERY: " + service_description + " on " + hostname + " is " + service_state +
                        "\nInformation: " + service_info)
else:
    notification = "I can't understand this notification :("


def send_message(server_address, server_port, chat, message):
    '''
    Connect to the 'serveraddress' on 'serverport' and deliver our 'message' at the chat named 'chatname'
    '''
    # Construct the message the way SkyBot is expecting it.
    msg = "[" + chat + "][opsview] echo " + message
    # Create a socket. Connect. Send. Close.
    soc = socket.socket()
    try:
        soc.connect((server_address, port))
    except socket.error, err:
        print "Connection to %s on port %s failed: %s" % (server_address, server_port, err)
        return False
    soc.send(msg)
    soc.close()
    return True


if __name__ == '__main__':
    send_message(skybot_server, port, chat_name, notification)
    #logger.info(notification)
